﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;

namespace KB.Logging
{
    public class SimpleWebLogger : ILogger
    {
        public string DirectoryVirtualPath { get; private set; }

        private readonly string _directoryPhysicalPath;
        public string DirectoryPhysicalPath
        {
            get { return _directoryPhysicalPath; }
        }

        private long _maxFileSize = 512 * 1024;
        public long MaxFileSize
        {
            get { return _maxFileSize; }
            set
            {
                if (value < 5 * 1024)
                {
                    throw new ArgumentException("Minimum 5 KB.");
                }
                _maxFileSize = value;
            }
        }

        private readonly string _fileName;

        public SimpleWebLogger()
            : this(String.Empty)
        {
        }

        public SimpleWebLogger(string fileName)
        {
            this._fileName = fileName;
            DirectoryVirtualPath = "~/Logs";
            _directoryPhysicalPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Logs");
        }

        #region ILogger Members

        public string NewLineChars
        {
            get { return Environment.NewLine; }
        }

        public void LogLine(string message, bool addTimeSpan)
        {
            Log(message + NewLineChars, addTimeSpan);
        }

        private string GetDateTimeStringForFileName(DateTime datetime)
        {
            return datetime.ToString().Replace('/', '-').Replace(':', '-');
        }

        public void Log(string message, bool addTimeSpan)
        {
            DateTime now = DateTime.Now;

            if (addTimeSpan)
            {
                message = "[" + now.ToString() + "]" + message;
            }

            if (!Directory.Exists(DirectoryPhysicalPath))
            {
                Directory.CreateDirectory(DirectoryPhysicalPath);
            }

            string fileName = _fileName;
            if (String.IsNullOrEmpty(fileName))
            {
                fileName = now.Year + "-" + now.Month + "-" + now.Day + ".txt";
            }
            string physicalFilePath = System.IO.Path.Combine(DirectoryPhysicalPath, fileName);

            if (File.Exists(physicalFilePath))
            {
                FileInfo fileInfo = new FileInfo(physicalFilePath);
                if (fileInfo.Length >= _maxFileSize)
                {
                    string backUpFileName = Path.GetFileNameWithoutExtension(fileInfo.Name) + ".bak-" + GetDateTimeStringForFileName(now) + ".txt";
                    fileInfo.MoveTo(Path.Combine(DirectoryPhysicalPath, backUpFileName));
                    File.WriteAllText(physicalFilePath, message, Encoding.UTF8);
                }
                else
                {
                    using (var writer = new StreamWriter(physicalFilePath, true, Encoding.UTF8))
                    {
                        writer.Write(message);
                        writer.Close();
                    }
                }
            }
            else
            {
                File.WriteAllText(physicalFilePath, message, Encoding.UTF8);
            }
        }

        #endregion
    }
}